from rediscluster import RedisCluster
from collections import defaultdict

# Redis 集群节点信息（至少提供一个节点的 IP 和端口）
nodes = [
    {"host": "172.16.25.101", "port": 10170},
    {"host": "172.16.25.101", "port": 10171},
    {"host": "172.16.25.101", "port": 10172},
    {"host": "172.16.25.102", "port": 10170},
    {"host": "172.16.25.102", "port": 10171},
    {"host": "172.16.25.102", "port": 10172},
    {"host": "172.16.25.103", "port": 10170},
    {"host": "172.16.25.103", "port": 10171},
    {"host": "172.16.25.103", "port": 10172}
]

cluster = RedisCluster(
    startup_nodes=nodes,
    decode_responses=True,
    ssl=True,
    skip_full_coverage_check=True,
    ssl_cert_reqs="required",
    ssl_ca_certs="F:/work/.tmp/ssl/25.101/acs-ca.crt",
    ssl_certfile="F:/work/.tmp/ssl/25.101/server.crt",
    ssl_keyfile="F:/work/.tmp/ssl/25.101/server.key",
    password="acsAdmin@2023033"
)

# 获取所有节点信息
_nodes = cluster.cluster_nodes()
# 初始化统计字典：{"host": {"master": 0, "slave": 0}}
host_stats = defaultdict(lambda: {"master": 0, "slave": 0})

# 统计主节点和从节点
masters = 0
slaves = 0

for node in _nodes:
    print(node)
    host = node["host"]
    if "master" in node["flags"]:
        host_stats[host]["master"] += 1
    elif "slave" in node["flags"]:
        host_stats[host]["slave"] += 1

# 打印结果
for host, stats in host_stats.items():
    print(f"Host {host}:")
    print(f"  Master nodes: {stats['master']}")
    print(f"  Slave nodes: {stats['slave']}\n")
